//
//  CountyViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/11/25.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "CountyViewController.h"
#import "SubVideoCollectionViewCell.h"
#import "NewsTableViewCell.h"
#import "NewsViewController.h"
#import "CountyVideoViewController.h"
#import "NewsDetailViewController.h"
#import "NewsDetailVC.h"

@interface CountyViewController () <UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

/** 导航条 */
@property (nonatomic, strong) UIImageView * navBar;
/** 主列表 */
@property (nonatomic, strong) UITableView * mainTableView;
/** 视频列表 */
@property (nonatomic, strong) UICollectionView * countyVideoCollectionView;
/** 视频数据源 */
@property (nonatomic, strong) NSMutableArray * countyVideoArr;
/** 视频列表布局 */
@property (nonatomic, strong) UICollectionViewFlowLayout * countyVideoFlowLayout;
/** 资讯列表 */
@property (nonatomic, strong) UITableView * newsTableView;
/** 资讯数据源 */
@property (nonatomic, strong) NSMutableArray * newsArr;
/** 视频播放器 */
@property (nonatomic, strong) MPMoviePlayerViewController * player;


@end

@implementation CountyViewController

- (MPMoviePlayerViewController *)player{
    if (!_player) {
        _player = [[MPMoviePlayerViewController alloc] init];
        _player.moviePlayer.shouldAutoplay = YES;
        _player.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;

    }
    return _player;
}

- (NSMutableArray *)newsArr{
    if (!_newsArr) {
        _newsArr = [NSMutableArray array];
    }
    return _newsArr;
}

- (NSMutableArray *)countyVideoArr{
    if (!_countyVideoArr) {
        _countyVideoArr = [NSMutableArray array];
    }
    return _countyVideoArr;
}

- (UITableView *)newsTableView{
    if (!_newsTableView) {
        _newsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, HeightScale(44), SCREEN_W, (self.mainTableView.frame.size.height - SCREEN_W / 1.15) - HeightScale(44) - HeightScale(10.000002)) style:UITableViewStylePlain];
        _newsTableView.delegate = self;
        _newsTableView.dataSource = self;
        _newsTableView.tableFooterView = [UIView new];
        _newsTableView.backgroundColor = COLOR_LIGHTBGCOLOR;
        _newsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _newsTableView;
}

- (UICollectionViewFlowLayout *)countyVideoFlowLayout{
    if (!_countyVideoFlowLayout) {
        _countyVideoFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _countyVideoFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
    return _countyVideoFlowLayout;
}

- (UICollectionView *)countyVideoCollectionView{
    if (!_countyVideoCollectionView) {
        _countyVideoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HeightScale(44), SCREEN_W, SCREEN_W / 1.15 - HeightScale(44)) collectionViewLayout:self.countyVideoFlowLayout];
        _countyVideoCollectionView.delegate = self;
        _countyVideoCollectionView.dataSource = self;
        _countyVideoCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        [_countyVideoCollectionView registerClass:[SubVideoCollectionViewCell class] forCellWithReuseIdentifier:@"countyVideoCell"];
    }
    return _countyVideoCollectionView;
}

- (UITableView *)mainTableView{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_W, SCREEN_H - 64 - 49) style:UITableViewStyleGrouped];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.backgroundColor = COLOR_DEEPBGCOLOR;
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestAll)];
    }
    return _mainTableView;
}

- (UIImageView *)navBar{
    if (!_navBar) {
        _navBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 64)];
        _navBar.image = ImageNamed(@"daohangtiao");
    }
    return _navBar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"县域特色";
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.mainTableView];
    
    
    [self requestCountyVideo];
    
    [self requestCountyNews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoFinished) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestAll) name:@"loginSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestAll) name:@"logoutSuccess" object:nil];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.1 animations:^{
        [AppDelegate shareDelegate].tabBar.customBar.center = CGPointMake(SCREEN_W / 2, SCREEN_H - [AppDelegate shareDelegate].tabBar.customBar.frame.size.height / 2);
    }];
    
    [Tool setNavigationBarType:self];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - UITableView & UITableViewDataSource Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([tableView isEqual:self.mainTableView]) {
        return 2;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.mainTableView]) {
        return 1;
    } else {
        return (self.newsArr.count >= 4) ? 4 : self.newsArr.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.mainTableView] && indexPath.section == 0) {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, HeightScale(15), WidthScale(3.5), HeightScale(14))];
        imageView.image = ImageNamed(@"矩形-75-拷贝-2");
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + WidthScale(15), 0, WidthScale(100), HeightScale(44))];
        titleLabel.text = @"县域特色";
        titleLabel.font = FONTSIZE(17);
        titleLabel.textColor = COLOR_FONTBLACK;
        
        UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(54), 0, WidthScale(44), HeightScale(44))];
        [moreButton setImage:ImageNamed(@"more") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [moreButton initWithBlock:^(id obj) {
            DLog(@"视频更多");
            CountyVideoViewController *countyVideoVC = [[CountyVideoViewController alloc] init];
            countyVideoVC.title = @"县域特色";
            [weakSelf.navigationController pushViewController:countyVideoVC animated:YES];
            
        } for:UIControlEventTouchUpInside];
        
        [cell.contentView addSubview:imageView];
        
        [cell.contentView addSubview:titleLabel];
        
        [cell.contentView addSubview:moreButton];
        
        [cell.contentView addSubview:self.countyVideoCollectionView];
        
        cell.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    } else if ([tableView isEqual:self.mainTableView] && indexPath.section == 1) {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, HeightScale(15), WidthScale(3.5), HeightScale(14))];
        imageView.image = ImageNamed(@"矩形-75-拷贝-2");
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + WidthScale(15), 0, WidthScale(100), HeightScale(44))];
        titleLabel.text = @"热点资讯";
        titleLabel.font = FONTSIZE(17);
        titleLabel.textColor = COLOR_FONTBLACK;
        
        UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(54), 0, WidthScale(44), HeightScale(44))];
        [moreButton setImage:ImageNamed(@"more") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [moreButton initWithBlock:^(id obj) {
            DLog(@"资讯更多");
            NewsViewController *newsVC = [[NewsViewController alloc] init];
            newsVC.title = @"县域特色";
            [weakSelf.navigationController pushViewController:newsVC animated:YES];
            
        } for:UIControlEventTouchUpInside];
        
        [cell.contentView addSubview:imageView];
        
        [cell.contentView addSubview:titleLabel];
        
        [cell.contentView addSubview:moreButton];
        
        cell.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        [cell.contentView addSubview:self.newsTableView];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    } else {
        //资讯列表
        static NSString *cellID = @"newsCell";
        NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        
        cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.newsArr[indexPath.row][@"title"]];
        
        cell.timeLabel.text = [NSString stringWithFormat:@"%@", self.newsArr[indexPath.row][@"publishTime"]];
        
        
        NSString *imagePath = [NSString stringWithFormat:@"%@%@", KHostAddress, self.newsArr[indexPath.row][@"imagePath"]];
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:nil];
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.mainTableView]) {
        if (indexPath.section == 0) {
            return SCREEN_W / 1.15;
        } else {
            return self.mainTableView.frame.size.height - SCREEN_W / 1.15 - HeightScale(10.000002);
        }
    } else {
        return HeightScale(104);
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:self.mainTableView]) {
        return 0.000001;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if ([tableView isEqual:self.mainTableView]) {
        if (section == 0) {
            return WidthScale(10);
        } else {
            return 0.000001;
        }
    } else {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.newsTableView]) {
        NewsDetailVC *newsDetailVC = [[NewsDetailVC alloc] init];
        newsDetailVC.dataDic = self.newsArr[indexPath.row];
        [self.navigationController pushViewController:newsDetailVC animated:YES];
//        NewsDetailViewController *newsDetailVC = [[NewsDetailViewController alloc] init];
//        newsDetailVC.dataDic = self.newsArr[indexPath.row];
//        [self.navigationController pushViewController:newsDetailVC animated:YES];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UICollectionDelegate & UICollectionViewDataSource Methods

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return (self.countyVideoArr.count >= 4) ? 4 : self.countyVideoArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SubVideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"countyVideoCell" forIndexPath:indexPath];
    if (self.countyVideoArr[indexPath.row][@"filepath"] == nil) {
        cell.playImageView.hidden = YES;
    } else {
        cell.playImageView.hidden = NO;
    }
    NSString *coverimagefile = [NSString stringWithFormat:@"%@%@", KHostAddress, self.countyVideoArr[indexPath.row][@"coverimagefile"]];
    [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverimagefile] placeholderImage:ImageNamed(@"placeholdershipin")];
    
    cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.countyVideoArr[indexPath.row][@"name"]];

    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(WidthScale(190), HeightScale(144));
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return WidthScale(10);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return HeightScale(15);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(HeightScale(0), WidthScale(10), HeightScale(0), WidthScale(10));
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DLog(@"index = %ld", indexPath.row);

    if ([self.countyVideoArr[indexPath.row][@"filepath"] isKindOfClass:[NSNull class]]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"视频地址不存在" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    } else if (self.countyVideoArr[indexPath.row][@"filepath"] == nil) {
        NewsDetailVC *newsDetailVC = [[NewsDetailVC alloc] init];
        newsDetailVC.dataDic = self.countyVideoArr[indexPath.row];
        [self.navigationController pushViewController:newsDetailVC animated:YES];
//        NewsDetailViewController *newsDetailVC = [[NewsDetailViewController alloc] init];
//        newsDetailVC.dataDic = self.countyVideoArr[indexPath.row];
//        [self.navigationController pushViewController:newsDetailVC animated:YES];
    }
    
    else {
        NSString *url = [NSString stringWithFormat:@"%@%@", KHostAddress, self.countyVideoArr[indexPath.row][@"filepath"]];
        self.player.moviePlayer.contentURL = [NSURL URLWithString:url];
        [self.player.moviePlayer.view setFrame:self.view.bounds];
        [self presentViewController:self.player animated:YES completion:^{
//            [self requestHistory:indexPath ID:self.countyVideoArr[indexPath.row][@"did"]];
            [self requestStatistics:indexPath ID:self.countyVideoArr[indexPath.row][@"id"]];
            //县域视频不用记录浏览历史
            [self noMoreVideos];
        }];
        
    }
    
    
}

#pragma mark - MPMoviePlayerPlaybackDidFinishNotification Method

- (void)videoFinished{
    DLog(@"停止播放");
    if (self.player) {
        self.player = nil;
    }
}

- (void)noMoreVideos{
    
    for (UIView *subView in self.player.view.subviews) {
        DLog(@"%@", subView);
        for (UIView *subview in subView.subviews) {
            DLog(@"subView %@", subview);
            for (UIView *subView2 in subview.subviews) {
                for (UIView *subview3 in subView2.subviews) {
                    for (UIView *subview4 in subview3.subviews) {
                        for (UIView *subview5 in subview4.subviews) {
                            if ([subview5 isKindOfClass:[UIButton class]]) {
                                DLog(@"%@", subview5);
                                if (subview5.frame.size.width == 32) {
                                    UIButton *button = (UIButton *)subview5;
                                    [button removeTarget:nil
                                                  action:NULL
                                        forControlEvents:UIControlEventAllEvents];
                                    [button initWithBlock:^(id obj) {
                                        [ZRProgressHUD showMsgWithoutView:@"没有更多了"];
                                    } for:UIControlEventTouchUpInside];
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#pragma mark - data request

/** 县域 - 视频 */
- (void)requestCountyVideo{
    NSString *URL = [NSString stringWithFormat:KCountyVideo, KHostAddress, @(1), KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            
            [self.countyVideoArr removeAllObjects];
            [self.countyVideoArr addObjectsFromArray:responseObject[@"data"][@"items"]];
            [self.countyVideoCollectionView reloadData];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 县域特色 - 新闻资讯 */
- (void)requestCountyNews{
    NSString *URL = [NSString stringWithFormat:KNEWSURL, KHostAddress, @(1), KOrganizationID];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            
            [self.newsArr removeAllObjects];
            [self.newsArr addObjectsFromArray:responseObject[@"data"][@"items"]];
            [self.newsTableView reloadData];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 添加浏览历史 */
- (void)requestHistory:(NSIndexPath *)indexPath ID:(NSString *)ID{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        
        NSString *URL = [NSString stringWithFormat:KaddHistory, KHostAddress, ID, @(2), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            DLog(@"添加浏览历史");
        } failure:^(NSError *error) {
            DLog(@"添加浏览历史失败");
        }];
    }
}

/** 添加统计 */
- (void)requestStatistics:(NSIndexPath *)indexPath ID:(NSString *)ID{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        //1、图书；2、视频；3、音频；4、期刊杂志5、县域视频6、资讯
        NSString *URL = [NSString stringWithFormat:Kstatistics, KHostAddress, KCurrentIP, [AppDelegate shareDelegate].userModel.userId, KOrganizationID, @(5), ID];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加统计成功");
            } else {
                DLog(@"添加统计失败");
            }
        } failure:^(NSError *error) {
            DLog(@"%@", error);
        }];
    }
}

- (void)requestAll{
    [self requestCountyVideo];
    [self requestCountyNews];
    
    [self.mainTableView.mj_header endRefreshing];
}

@end
